package com.yellowframework.cloud.interceptor;

import com.yellowframework.cloud.common.constant.Constants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Objects;

/**
 * Feign拦截器
 *
 * @author Hao.
 * @version 1.0
 * @date 2020/11/8 9:37
 */
public class FeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 使用RequestContextHolder工具获取request相关变量
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            // 取出request
            HttpServletRequest request = attributes.getRequest();
            final Object feign_login_key = request.getAttribute(Constants.FEIGN_LOGIN_KEY);
            // 设置feign免登录通行证
            if (Objects.nonNull(feign_login_key)) {
                requestTemplate.header(Constants.FEIGN_LOGIN_KEY.replace(":", ""), (String) feign_login_key);
            }

            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    if ("authorization".equals(name)) {
                        // System.out.println("name="+name+"values="+values);
                        requestTemplate.header(name, request.getHeader(name));
                    }
                }
            }
        }
    }
}
